package ink.tsg.thymeleaflayui.utils;

import java.io.*;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;

public class TcpClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket();
        //设置 超时时间
        socket.setSoTimeout(3000);
        //连接本地 端口2000 超时时间为3000毫秒
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(),2000), 3000);

        System.out.println("已经发起服务器连接。。。");
        System.out.println("客户端信息：" + socket.getLocalAddress() + "：" + socket.getLocalPort());
        System.out.println("服务器信息：" + socket.getInetAddress() + ":" + socket.getPort());
        try {
            todo(socket);
        }catch (Exception e) {
            System.out.println("异常关闭");
        }
        socket.close();
        System.out.println("客户端退出");
    }

    private static void todo(Socket client) throws IOException {
        InputStream in = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(in));

        //得到输出流
        OutputStream out = client.getOutputStream();
        PrintStream printStream = new PrintStream(out);

        //得到输入流　
        InputStream inputStream = client.getInputStream();
        BufferedReader buf = new BufferedReader(new InputStreamReader(inputStream));

        boolean flag = true;
        do {
            String str = input.readLine();
            //发送到服务器
            printStream.println(str);

            String echo = buf.readLine();

            if ("bye".equalsIgnoreCase(echo)) {
                flag = false;
            } else {
                System.out.println(echo);
            }
        }while (flag);
        buf.close();
        printStream.close();
        System.out.println("客户端已关闭");

    }
}
